﻿#include "countdownwidget.h"
#include "ui_countdownwidget.h"

CountdownWidget::CountdownWidget( QWidget* parent ) : QDialog( parent ), ui( new Ui::CountdownWidget ), msgbox_time_( 0 ), totalTime( 0 ), interval( 1 ) {
    ui->setupUi( this );
    setWindowTitle( "提示" );
    this->setWindowFlags( Qt::WindowStaysOnTopHint );
    QString button_style( "QPushButton{border-image: url(:/pic/src/button/key.png);color: white;}"
                          "QPushButton:hover{border-image: url(:/pic/src/button/key_hover.png);color: white;}"
                          "QPushButton:pressed{border-image: url(:/pic/src/button/key_pressed.png);color: black;}" );
    ui->pushButton_ok->setStyleSheet( button_style );
    ui->pushButton_cancel->setStyleSheet( button_style );
    ui->label->setText( "已到达目标点" );
}

CountdownWidget::~CountdownWidget() {
    timer_countdown->stop();
    delete ui;
    delete timer_countdown;
}

bool CountdownWidget::isOk() {
    return is_ok;
}

void CountdownWidget::startCountdownTimer( int t ) {
    totalTime       = t;
    timer_countdown = new QTimer( this );
    connect( timer_countdown, SIGNAL( timeout() ), this, SLOT( count_time() ) );
    timer_countdown->start( interval * 1000 );
}

void CountdownWidget::on_pushButton_cancel_clicked() {
    closeEnable = true;
    is_ok       = false;
    this->close();
}

void CountdownWidget::on_pushButton_ok_clicked() {
    closeEnable = true;
    is_ok       = true;
    this->close();
}

void CountdownWidget::setMessageText( QString str ) {
    ui->label->setText( str );
}

void CountdownWidget::count_time() {
    int letf_time = static_cast< int >( totalTime - msgbox_time_ );

    if ( letf_time <= 0 ) {
        ui->pushButton_cancel->click();  // 倒计时结束，默认按下取消按键
        this->close();
    }
    else {
        this->setWindowTitle( QString( "提示(%1)" ).arg( letf_time ) );
    }
    msgbox_time_ += interval;
}

void CountdownWidget::setCountdownTotalTime( int t ) {
    totalTime = t;
}

void CountdownWidget::setCountdownInterval( int t ) {
    interval = t;
}

void CountdownWidget::setButtonHide( CountdownWidget::Button btn ) {
    switch ( btn ) {
    case CountdownWidget::Button_Ok:
        ui->pushButton_ok->setHidden( true );
        break;

    case CountdownWidget::Button_Cancel:
        ui->pushButton_cancel->setHidden( true );
        break;
    }
}

void CountdownWidget::closeEvent( QCloseEvent* event ) {
    if ( !closeEnable ) {
        event->ignore();
    }
}

void CountdownWidget::setCloseEnable( bool sw ) {
    closeEnable = sw;
}
